<template>
  <div>
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.go(-1)" />

    <div class="avatar">
      <van-image
        width="120"
        height="120"
        fit="cover"
        round
        :src="userInfo.photo"
      />
      <van-uploader :after-read="afterRead" />
    </div>

    <van-cell-group>
      <van-cell
        title="名称"
        :value="userInfo.name"
        is-link
        @click="showDialogClick"
      />
      <van-cell
        title="性别"
        :value="userInfo.gender ? '女' : '男'"
        is-link
        @click="showPopup = true"
      />
      <van-cell
        title="生日"
        :value="userInfo.birthday"
        is-link
        @click="showPickerClick"
      />
    </van-cell-group>

    <!-- 编辑用户名 -->
    <van-dialog
      v-model="showDialog"
      title="用户名编辑"
      show-cancel-button
      @confirm="confirmName"
    >
      <van-field ref="filed" v-model="newName" placeholder="请输入用户名" />
    </van-dialog>

    <!-- 编辑性别弹窗 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-nav-bar
        title="编辑性别"
        left-arrow
        @click-left="showPopup = false"
      />

      <van-cell title="男" is-link @click="editGender(0)" />
      <van-cell title="女" is-link @click="editGender(1)" />
    </van-popup>

    <!-- 编辑生日弹窗 -->
    <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showPicker = false"
        @confirm="editBirthday"
      />
    </van-popup>

    <!-- 编辑头像 -->
    <div class="cropper" v-show="showCropper">
      <vueCropper
        ref="cropper"
        :img="img"
        autoCrop
        autoCropWidth="120"
        autoCropHeight="120"
      ></vueCropper>
      <van-button type="primary" class="cancel" @click="showCropper = false"
        >取消</van-button
      >
      <van-button type="info" class="confirm" @click="editPhoto"
        >确认</van-button
      >
    </div>
  </div>
</template>

<script>
// 导入mapState
import { mapState } from 'vuex'
// 导入接口
import { editUserInfo, editPhoto } from './user.js'
// 导入moment插件
import * as moment from 'moment'
// 导入图片裁切插件
import { VueCropper } from 'vue-cropper'
export default {
  name: 'edit',
  components: {
    VueCropper
  },
  data () {
    return {
      showDialog: false,
      showPopup: false,
      showPicker: false,
      newName: '',
      minDate: new Date(1995, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      img: '',
      showCropper: false
    }
  },
  methods: {
    showDialogClick () {
      this.showDialog = true
      this.newName = this.userInfo.name
      // 独属于vue的定时器
      // vue渲染Dom是一个异步的过程，所以走到下面这个代码时，其实还没有显示出来输入框
      // this.$refs.filed.focus()
      // this.$nextTick()这个方法等当前作用域内的异步代码走完才执行内部的代码
      this.$nextTick(() => {
        this.$refs.filed.focus()
      })
    },
    confirmName () {
      editUserInfo({ name: this.newName }).then(res => {
        // console.log(res);
        // 弹窗提示
        this.$toast.success('修改成功')
        // 更新vuex中的数据
        this.$store.commit('updateUserInfo', {
          ...this.userInfo,
          name: this.newName
        })
      })
    },
    editGender (gender) {
      editUserInfo({ gender }).then(res => {
        // console.log(res);
        // 弹窗提示
        this.$toast.success('修改成功')
        this.$store.commit('updateUserInfo', {
          ...this.userInfo,
          gender
        })
        this.showPopup = false
      })
    },
    showPickerClick () {
      this.showPicker = true
      // 因为下面moment转格式时需要是一个对象而不是字符串，所以在这里就需要转成对象格式
      let date = new Date(this.userInfo.birthday)
      this.currentDate = date
    },
    editBirthday () {
      // console.log(111);
      let birthday = moment(this.currentDate).format('YYYY-MM-DD')
      // console.log(date);
      editUserInfo({ birthday }).then(res => {
        // console.log(res);
        // 弹窗提示
        this.$toast.success('修改成功')
        this.$store.commit('updateUserInfo', {
          ...this.userInfo,
          birthday
        })
        this.showPicker = false
      })
    },
    // 头像
    afterRead (file) {
      // console.log(file.file);  //原始的file对象
      // console.log(file.content);  //base64
      // 裁切框不支持原本的file对象，但支持base64格式
      this.img = file.content
      this.showCropper = true
    },
    editPhoto () {
      // 获取截图的blob数据
      this.$refs.cropper.getCropBlob(data => {
        // do something
        // console.log(data)
        // formData上传文件支持file对象和blob格式
        let fd = new FormData()
        fd.append('photo', data)
        editPhoto(fd).then(res => {
          // console.log(res);
          //弹窗
          this.$toast.success('修改成功')
          // 关闭裁切框
          this.showCropper=false
          this.$store.commit('updateUserInfo', {
            ...this.userInfo,
            photo: res.data.data.photo
          })
        })
      })
    }
  },
  computed: {
    ...mapState(['userInfo'])
  }
}
</script>

<style lang="less">
.avatar {
  height: 160px;
  display: flex;
  justify-content: center;
  align-items: center;

  .van-uploader {
    width: 120px;
    height: 120px;
    position: absolute;
    opacity: 0;
    .van-uploader__upload {
      width: 120px;
      height: 120px;
    }
  }
}

.cropper {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  .cancel {
    position: absolute;
    left: 0;
    bottom: 0;
  }

  .confirm {
    position: absolute;
    right: 0;
    bottom: 0;
  }
}
</style>
